package web;

import java.io.IOException;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ComponentSystemEvent;
import javax.faces.model.ListDataModel;
import javax.inject.Inject;

import facade.ClubFacade;
import facade.dto.ClubDTO;

@ManagedBean
@ViewScoped
public class ClubBean {
	
	private ListDataModel<ClubDTO> model;
	
	@Inject
	private ClubFacade clubService;
	
	private ClubDTO newClub = new ClubDTO();
	private ClubDTO clubToDelete = null;
	
	public ClubBean() {
		
	}
	
	public void init(ComponentSystemEvent event) {
		List<ClubDTO> clubs = clubService.getAll();
		model = new ListDataModel<ClubDTO>(clubs);
	}
	
	public ListDataModel<ClubDTO> getModel() {
		return model;
	}

	public void setModel(ListDataModel<ClubDTO> model) {
		this.model = model;
	}
	
	public void add() {
		ClubDTO club = clubService.createClub(newClub);
		if (club == null) {
			return;
		}
		FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Club "+club.getName()+" added!", null));
		model = new ListDataModel<ClubDTO>(clubService.getAll());
	}

	public void remove() throws IOException {
		if (clubToDelete == null) {
			return;
		}
		clubService.removeClub(clubToDelete.getId());
		FacesContext.getCurrentInstance().getExternalContext().redirect("club.xhtml");
		FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, null, "Club deleted!"));
	}
	
	public ClubDTO getNewClub() {
		return newClub;
	}

	public void setNewClub(ClubDTO newClub) {
		this.newClub = newClub;
	}

	public ClubDTO getClubToDelete() {
		return clubToDelete;
	}

	public void setClubToDelete(ClubDTO clubToDelete) {
		this.clubToDelete = clubToDelete;
	}
}
